package com.smiier.skin.utils;

import java.util.ArrayList;
import java.util.Locale;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

import com.evan.common.utils.CacheCommon;
import com.evan.common.utils.CommonDBUtility;
import com.evan.common.utils.Cursor2Object;
import com.smiier.skin.vo.Keyword;
import com.smiier.skin.vo.TipMessageVo;

public class DBUtil extends CommonDBUtility {
	private final static String DATABASE_NAME = "skin.db";
	// private final static int DATABASE_VERSION = 6;

	private final static int DATABASE_VERSION = 7;

	private static final Class<?>[] tables = { Keyword.class,
			CacheCommon.class, TipMessageVo.class };

	private static DBUtil dbUtil;

	private SQLiteDatabase db;

	public static DBUtil getInstance(Context context) {
		if (dbUtil == null) {
			dbUtil = new DBUtil(context);
		}
		return dbUtil;
	}

	public DBUtil(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		db = getWritableDatabase();
	}

	public DBUtil(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		this.db = db;
		createTables();
	}

	public void createTables() {
		try {
			for (Class<?> table : tables) {
				db.execSQL("DROP TABLE IF EXISTS " + table.getSimpleName());
				db.execSQL("DROP TABLE IF EXISTS "
						+ table.getSimpleName()
								.toLowerCase(Locale.getDefault()));
				try {
					db.execSQL(generateSql(table));
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//		onCreate(db);
		
		  int upgradeVersion  = oldVersion;  
		  
		  
		    if (upgradeVersion != newVersion) {  
		        // Drop tables  
//		        db.execSQL("DROP TABLE IF EXISTS " + tableName);  
		    	
		        // Create tables  
		        onCreate(db);  
		    }  
	}

	/**
	 * 
	 * @Title: query
	 * @Description: TODO
	 * @param @param tableName
	 * @param @param selection like "id=?,name=?"
	 * @param @param selectionArgs like new String[]{1, zhangsan}
	 * @param @param orderBy
	 * @param @return
	 * @param @throws BarsearchException
	 * @return List<?>
	 * @throws
	 */
	public <T> ArrayList<T> query(Class<T> clazz, String[] columns,
			String selection, String[] selectionArgs, String orderBy) {
		ArrayList<T> list = new ArrayList<T>();
		Cursor cursor = null;
		try {
			cursor = db.query(clazz.getSimpleName(), columns, selection,
					selectionArgs, null, null, orderBy);
			while (cursor.moveToNext()) {
				list.add((T) Cursor2Object.parseDataSource(clazz, cursor));
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			closeCursor(cursor);
		}
		return list;
	}

	public void delete(String tableName, String whereClause, String[] whereArgs) {
		Cursor cursor = null;
		try {
			StringBuilder sql = new StringBuilder("delete from ");
			sql.append(tableName);
			if (whereClause != null)
				sql.append(whereClause);
			cursor = db.rawQuery(sql.toString(), whereArgs);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			closeCursor(cursor);
		}
	}

	/**
	 * @Title: getCount
	 * @Description: get count form given table by selectionArgs
	 * @param @param tableName
	 * @param @return
	 * @param @throws BarsearchException
	 * @return int
	 * @throws
	 */
	public int getCount(String tableName, String selection,
			String[] selectionArgs) {
		int count = 0;
		Cursor cursor = null;
		try {
			StringBuilder sql = new StringBuilder("select count(*) from ");
			sql.append(tableName);
			if (selection != null)
				sql.append(" ").append(selection);
			cursor = db.rawQuery(sql.toString(), selectionArgs);

			if (null != cursor) {
				if (cursor.getCount() > 0) {
					cursor.moveToFirst();
					count = cursor.getInt(0);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			closeCursor(cursor);
		}
		return count;
	}

	public synchronized long insert(String tableName, ContentValues values) {
		long id = db.insert(tableName, null, values);

		Log.i("testtip", "db.insert.id:" + id);
		return id;
	}

	void closeCursor(Cursor cursor) {
		if (!CommonUtility.isNull(cursor) && !cursor.isClosed()) {
			cursor.close();
		}
	}

	public void release() {
		if (!CommonUtility.isNull(db) && db.isOpen()) {
			db.close();
		}
	}
}
